package com.fan.txl.ui;

import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
//import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.widget.Toast;

import com.base.txl.utils.RxUtils;
import com.elvishew.xlog.XLog;
import com.fan.txl.R;
import com.fan.txl.data.Friend;
import com.fan.txl.data.base.Rsp;
import com.fan.txl.databinding.ActivityFriendsBinding;
import com.fan.txl.listener.OnClick;
import com.fan.txl.mock.api.service.APIService;
import com.fan.txl.mock.api.service.FriendService;
import com.fan.txl.mock.api.service.mock.MockFriendService;
import com.fan.txl.ui.adapter.BindAdapt;
import com.fan.txl.ui.adapter.FriendsBindAdapt;
import com.fan.txl.ui.base.RxActivity;
import com.fan.txl.ui.routers.ComponentRouters;
import com.fan.txl.utils.RecyclerViewUtils;
import com.github.mzule.activityrouter.annotation.Router;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.observers.DisposableObserver;

//data bind http://www.jianshu.com/p/b1df61a4df77
//SearchView	setOnSearchClickListener(View.OnClickListener)	android:onSearchClick
@Router({"http://mzule.com/main",ComponentRouters.friends})
public class FriendsUI extends RxActivity implements OnClick {

    BindAdapt<Friend> mAdapt;
    List<Friend> mFriends = new ArrayList<Friend>();


    @Override
    public boolean onSearchRequested() {
        return super.onSearchRequested();
    }

    @Override
    public boolean onSearchRequested(SearchEvent searchEvent) {
        return super.onSearchRequested(searchEvent);
    }



    /*RxSearchView.queryTextChangeEvents(searchView).debounce(400,TimeUnit.MILLISECONDS).
    observeOn(AndroidSchedulers.mainThread()).
    subscribeOn(Schedulers.newThread()).
    skip(2).
    map(searchViewQueryTextEvent -> searchViewQueryTextEvent.queryText().toString()).
    flatMap(s -> RestWebClient.get().getSearchedGifs(s,"dczC")).
    subscribe(OnNextAction,onErrorAction);
    */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         ActivityFriendsBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_friends);
         binding.setFriendsEvent(this);

        setSupportActionBar(binding.toolbar);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        //歌曲模式
        binding.toolbar.setTitle("任贤齐");
        binding.toolbar.setSubtitle("伤心太平洋");

        mAdapt= new FriendsBindAdapt(mFriends);
        binding.friends.setLayoutManager(RecyclerViewUtils.getFlexMgr());


        binding.friends.setAdapter(mAdapt); //adapt.notifyItemInserted(),adapt.notifyItemRemoved(),adapt.notifyItemChanged() //friends.setOnFlingListener();
        handleIntent(getIntent());

        //authService();
        //FriendsService();
        mockFriendsService();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }


    private void handleIntent(Intent intent){
        if (Intent.ACTION_SEARCH.equals(intent.getAction())){
            String query = intent.getStringExtra(SearchManager.QUERY);
            Friend friends= new Friend();
            friends.setName(query);
            friends.setScore("222");
            mAdapt.getData().clear();
            mAdapt.getData().add(friends);
            mAdapt.notifyDataSetChanged();
        }
    }

    public void mockFriendsService(){
        getMockAPIService()
                .getFriendService()
        .friends()
        .compose(RxUtils.<Rsp<List<Friend>>>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
        .compose(this.<Rsp<List<Friend>>>bindUntilEvent(ActivityEvent.STOP))
        .subscribe(new DisposableObserver<Rsp<List<Friend>>>() {
            @Override
            protected void onStart() {
                super.onStart();
            }

            @Override
            public void onNext(Rsp<List<Friend>> rsp) {
                mAdapt.getData().addAll(rsp.getData());
                mAdapt.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                e.getMessage();
            }

            @Override
            public void onComplete() {
                XLog.d("onComplete");
            }
        });
    }

    public void FriendsService(){
        getAPIService()
                .getFriendService()
                .friends()
                .compose(RxUtils.<Rsp<List<Friend>>>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<Rsp<List<Friend>>>bindUntilEvent(ActivityEvent.STOP))
                .subscribe(new DisposableObserver<Rsp<List<Friend>>>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onNext(Rsp<List<Friend>> rsp) {
                        mAdapt.getData().addAll(rsp.getData());
                        mAdapt.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.getMessage();
                    }

                    @Override
                    public void onComplete() {
                        XLog.d("onComplete");
                    }
                });
    }




    @Override
    public void click(View view) {
        Friend friend=  mAdapt.getData().get(0);
        friend.setName("王五");
        friend.setScore("102");
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case  android.R.id.home:
                Toast.makeText(this, "nav", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        SearchManager searchManager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
        SearchableInfo searchableInfo= searchManager.getSearchableInfo(getComponentName());
        //SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));

        searchView.setSearchableInfo(searchableInfo);
        return true;
    }

}
